package model.mediators;

import java.util.Iterator;

import model.item.Inventory;
import model.item.InventoryItem;

public class ShopMediator extends InteractionMenuMediator {

	private Inventory patron;
	private Inventory shopkeeper;
	private int bargain;
	private int favor;
	private InteractiveMediator parentMediator;
	private WindowedItemInteraction window;

	/**
	 * @param partron
	 * @param shopkeeper
	 * @param partron_bargain
	 * @param shopKeeper_favor
	 */
	public ShopMediator(Inventory patron, Inventory shopkeeper,
			int bargain, int favor, InteractiveMediator parentMediator) {
		this.patron = patron;
		this.shopkeeper = shopkeeper;
		this.bargain = bargain;
		this.favor = favor;
		this.parentMediator = parentMediator;
		init();
	}
		
public void init() {
		
		if (favor >= 25) {
		window = new WindowedItemInteraction("Shop", this);
		Iterator<InventoryItem> activeIterator = patron.getInventory();
		Iterator<InventoryItem> passiveIterator = shopkeeper.getInventory();
		while (activeIterator.hasNext()) {
			InventoryItem nextItem = activeIterator.next();
			int valueIncludingBargain = nextItem.getValue()*(100 + bargain)/200;
			window.addOptionLeft(new ItemInteractionOption(nextItem.getName(), nextItem) {
				public void actionPerformed() {
					buyItem(getItem());
					window.removeInteractionOption(this);
					window.refresh();
					
				}
			}, valueIncludingBargain); 
		}
		while (passiveIterator.hasNext()) {
			InventoryItem nextItem = passiveIterator.next();
			int valueIncludingBargain = nextItem.getValue()*(300 - bargain)/200;
			window.addOptionRight(new ItemInteractionOption(nextItem.getName(), nextItem) {
				public void actionPerformed() {
					sellItem(getItem());
					window.removeInteractionOption(this);
					window.refresh();
				}
			}, valueIncludingBargain); 
		}
		
		
		window.createWindow();
		}
		
		else {
			WindowedInteraction failWindow = new WindowedInteraction("Not Enough Favorability", this);
			failWindow.createWindow();
		}
	}
	
	public void exit() {
		parentMediator.show();
	}
	
	private void buyItem(InventoryItem item) {
		int valueIncludingBargain = item.getValue()*(300 - bargain)/200;
		transact(item, patron, shopkeeper, valueIncludingBargain);
		
	}
	
	private void sellItem(InventoryItem item) {
		int valueIncludingBargain = item.getValue()*(100 + bargain)/200;
		transact(item, shopkeeper, patron, valueIncludingBargain);
	}
	
	private void transact(InventoryItem item, Inventory buyer, Inventory seller, int valueIncludingBargain) {
		if (buyer.canReceive(item) && buyer.canAfford(valueIncludingBargain)) {
			buyer.removeGold(valueIncludingBargain);
			seller.addGold(valueIncludingBargain);
			seller.removeItem(item);
			buyer.addItem(item);
		}
	}
}
